package com.example.app2

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController


class DetailFragment : Fragment() {
    var myViewModel: MyViewModel? = null
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.e("DetailFragment", "onCreateView")
        val view = inflater.inflate(R.layout.fragment_detail, container, false)
//        requireActivity() 这里要传这个才能实现多个fragment数据共享
        myViewModel = ViewModelProvider(requireActivity()).get(MyViewModel::class.java)
        myViewModel?.text?.observe(viewLifecycleOwner, Observer {
            view.findViewById<TextView>(R.id.textView).text = it
        })
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.findViewById<
                Button>(R.id.button).setOnClickListener {
            findNavController().navigate(R.id.action_detailFragment_to_threeFragment)
        }

        view.findViewById<
                Button>(R.id.button2).setOnClickListener {
            val navigateUp = findNavController().navigateUp()//向上导航
//            Log.e("DetailFragment", "  3535345b  $navigateUp ")
        }

        view.findViewById<
                Button>(R.id.button4).setOnClickListener {

            /*          //返回到栈里的某个Fragment，会将在这需要跳转的Fragment的栈前的Fragment全部清出。
                      val bundle = Bundle()
                      bundle.putString("CITY_NAME_KEY", "beijin")
                      val navOptions = NavOptions.Builder()
                          .setPopUpTo(R.id.mainFragment, true) //要为true
          //                .setLaunchSingleTop(true)  //还可以设置单例模式
                          .build()


                      findNavController().navigate(
                          R.id.action_detailFragment_to_mainFragment,
                          bundle,
                          navOptions
                      )*/

            //第一个参数是：目的地，也就是
            //第二个数数是：目的地的fragment是否也弹出栈    当设为mainFragment时，又为true时，mainFragment也会被销毁。 再次从main跳时就会出错！
//            findNavController().popBackStack(R.id.mainFragment, false)
            findNavController().popBackStack(R.id.detailFragment, true)
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e("DetailFragment", "onDestroy")
    }
}